<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 * tag api
 */
namespace app\bbs\api;

use app\bbs\model\Tag;
use app\common\api\BaseApi;
use app\bbs\api\FilterKeyWordsApi;

class TagApi extends BaseApi{
	const ADD             = "bbs/TagApi/add";
	const ADD_ALL         = "bbs/TagApi/addAll";
	const SAVE            = "bbs/TagApi/save";
	const SAVE_BY_ID      = "bbs/TagApi/saveByID";
	const DELETE          = "bbs/TagApi/delete";
	const QUERY           = "bbs/TagApi/query";
	const QUERY_NO_PAGING = "bbs/TagApi/queryNoPaging";
	const GET_INFO        = "bbs/TagApi/getInfo";
	const UPDATE          = "bbs/TagApi/update";
	const SET_DEC         = "bbs/TagApi/setDec";
	const COUNT           = "bbs/TagApi/count";
	//自定义
	const SET_DEC2        = "bbs/TagApi/setDec2";
	const CHECK           = "bbs/TagApi/check";
	const ADD_S           = "bbs/TagApi/adds";
	const FIND_S          = "bbs/TagApi/finds";
	const GET_S           = "bbs/TagApi/gets";
	const EDIT_S          = "bbs/TagApi/edits";

	protected function _init(){
		$this -> model = new Tag();
	}

	/**
	 * 根据帖子ID获取标签信息
	 * @param  [type] $tid [description]
	 * @return [type]      [description]
	 */
	public function gets($tid=0){
		$tid = intval($tid);
		if($tid>0){
			$result = $this->model->alias('t')->where('`f`.`tid`='.$tid)
			->field('t.id,t.name,t.used')
			->join('LEFT JOIN itboye_tag_to_fthread as f on `f`.`tag_id`=`t`.`id`')
			->select();
			return $result ? $result : [];
		}else{
			return [];
		}
	}
	/**
	 * 获取$type类型的标签$number个
	 * @param  [type] $type   0=>随机,1=>最新,2=>最热
	 * @param  [type] $number [description]
	 * @return [type]         [description]
	 */
	public function finds($type,$number,$field){
		$type   = intval($type);
		$number = intval($number);
		$order  = 'id desc';
		$where  = ['_string'=>'used>0'];
		if(0 === $type){
			$order_1 = ['id','used','name','md5_name'];
			$order_2 = ['desc','asc'];
			$order = $order_1[array_rand($order_1)].' '.$order_2[array_rand($order_2)];
			//TODO 随机
			//http://zhidao.baidu.com/link?url=aKoTTv5xNPe5A5Vg8hkq4mKvujyX0X6Ni4TzlX75viAgEoXS0pPtzn91wD23QUTAlBzUoustZK7S7f7mMSkS-5gEsUlzc5m0aJqVe1KEKS3
			// $order = 'rand()';
			$max = intval($this->model->where($where)->count());
			if($max>1 && $max>$number){
				$start = floor(mt_rand(0,$max-$number-1));

			}else{
				$start = 0;
			}
			// trace('---'.$start.'---'.$number.'---'.$max);
			$res   = $this->model->where($where)->order($order)->limit($start,$number)->field($field)->select();
			if(false === $res) return $this->apiReturnErr($this->model->getDbError());
			return $this->apiReturnSuc($res);
				// $max -=1;
				// $ids = $this->getRandIds(0,$max,$number);
				// // trace('---ids---');
				// // trace($ids);
				// $result = [];
				// foreach ($ids as $v) {
				// 	$res = $this->model->order($order)->limit($v,1)->field($field)->find();
				// 	if(!$res) return $this->apiReturnErr($this->model->getDbError());
				// 	$result[] = $res;
				// }
				// return $this->apiReturnSuc($result);
			// }
		}else if(1 === $type){
			//最新
			$order = 'id desc';
		}else if(2 === $type){
			//最热
			$order = 'used desc';
		}
		// trace('---order---');
		// trace($order);
		$result = $this->model->where($where)->order($order)->limit($number)->field($field)->select();
		if(false === $result){
			return $this->apiReturnErr($this->model->getDbError());
		}else{
			return $this->apiReturnSuc($result);
		}
	}
	/**
	 * 标签批量添加 - tid无关 - 带检查
	 * @param  string  $str  [description]
	 * @param  boolean $flus 是否加1
	 * @param  int     $tid  thread-id
	 * @return [type]        [description]
	 */
	public function adds($str='',$flus=false,$tid=0){
		$result = $this->check($str);
		if(!$result['status']) return $this->apiReturnErr($result['info']);
		$tags = array_unique(explode(',', $str));
		foreach ($tags as $v) {
			$v = trim($v);
			if($v){
				$md5 = md5($v);
				$result = $this->getInfo(['md5_name'=>$md5]);
				if(!$result['status']) return $this->apiReturnErr($result['info']);
				if(empty($result['info'])){
					//add
					$map = [
						'name'     =>$v,
						'md5_name' =>$md5,
						'used'     =>($flus?1:0),
					];
					// trace($map);
					$result = $this->add($map);
					// trace($result);
					if(!$result['status']) return $this->apiReturnErr($result['info']);
					$id = $result['info'];
				}else{
					$id     = $result['info']['id'];
					if($flus){
						$used   = intval($result['info']['used'])+1;//used +1
						$result = $this->save(['id'=>$id],['used'=>$used]);
						if(!$result['status']) return $this->apiReturnErr($result['info']);
					}
				}
				if($tid){
					$r = apiCall(ForumThreadApi::GET_INFO,[['tid'=>$tid]]);
					if(!$r['status']) return $this->apiReturnErr($r['info']);
					if(empty($r['info'])) return $this->apiReturnErr('帖子不存在');
					$fid = $r['info']['fid'];
					$map = [
						'tid'    =>$tid,
						'fid'    =>$fid,
						'tag_id' =>$id,
					];
					$r = apiCall(TagToFthreadApi::ADD,[$map]);
					if(!$r['status']) return $this->apiReturnErr($r['info']);
				}
			}
		}
		return $this->apiReturnSuc('添加成功');
	}


	/**
	 * 帖子标签批量修改 - tid必须 - 带检查
	 * @param  string  $str  [description]
	 * @param  boolean $flus 是否加1
	 * @param  int     $tid  thread-id
	 * @return [type]        [description]
	 */
	public function edits($str = '',$flus = false,$tid = 0){
		//tid检测
		if(!$tid) return $this->apiReturnErr('tid错误');
		$r = apiCall(ForumThreadApi::GET_INFO,[['tid'=>$tid]]);
		if(!$r['status']) return $this->apiReturnErr($r['info']);
		if(empty($r['info'])) return $this->apiReturnErr('帖子不存在');
		$fid = $r['info']['fid'];
		//检查str
		$result = $this->check($str);
		if(!$result['status']) return $this->apiReturnErr($result['info']);
		//待添加tag_name
		$tags = array_unique(explode(',', $str));
		//已有tag_id
		$r = apiCall(TagToFthreadApi::QUERY_NO_PAGING,[['tid'=>$tid],false,'tag_id']);
		if(!$r['status']) return $this->apiReturnErr($r['info']);
		$tag_ids = [];
		foreach ($r['info'] as $v) {
			$tag_ids[] = $v['tag_id'];
		}
		//thread tag add
		foreach ($tags as $v) {
			if($v){
				$md5 = md5($v);
				$result = $this->getInfo(['md5_name'=>$md5]);
				if(!$result['status']) return $this->apiReturnErr($result['info']);
				if(empty($result['info'])){
					//tag表没有 new tag add
					$map = [
						'name'     =>$v,
						'md5_name' =>$md5,
						'used'     =>($flus?1:0),
					];
					// trace($map);
					$result = $this->add($map);
					// trace($result);
					if(!$result['status']) return $this->apiReturnErr($result['info']);
					$id = $result['info'];
					$map = [
						'tid'    => $tid,
						'fid'    => $fid,
						'tag_id' => $id,
					];
					$r = apiCall(TagToFthreadApi::ADD,[$map]);
					if(!$r['status']) return $this->apiReturnErr($r['info']);
				}else{
					//tag表有
					$id = $result['info']['id'];
					if(in_array($id, $tag_ids)){
						//帖子已包含 - 不做修改
						unset($tag_ids[array_search($id,$tag_ids)]);
					}else{
						//帖子未包含 - 关联帖子 used +1
						if($flus){
							$used   = intval($result['info']['used'])+1;//used +1
							$result = $this->save(['id'=>$id],['used'=>$used]);
							if(!$result['status']) return $this->apiReturnErr($result['info']);
						}
						$map = [
							'tid'    => $tid,
							'fid'    => $fid,
							'tag_id' => $id,
						];
						$r = apiCall(TagToFthreadApi::ADD,[$map]);
						if(!$r['status']) return $this->apiReturnErr($r['info']);
					}
				}
			}
		}
		$ids = implode(',', $tag_ids);
		if($ids){
			//取消帖子关联
			$map = [
			'tid'     =>$tid,
			'fid'     =>$fid,
			'_string' =>'tag_id in ('.$ids.')',
			];
			$r = apiCall(TagToFthreadApi::DELETE,[$map]);
			if(!$r['status']) return $this->apiReturnErr($r['info']);
			//used -1
			$map = [
			'_string' =>'id in ('.$ids.')',
			];
			$r = $this->setDec2($map,'used',1);
			if(!$r['status']) return $this->apiReturnErr($r['info']);
		}
		return $this->apiReturnSuc('修改成功');
	}

	/**
	 * 检查 和 过滤 - 只允许中文,多个用,分割
	 * @param  [type] $str [description]
	 * @return [type]      [description]
	 */
	public function check($str){
		//检查
		if(!preg_match('/^[0-9a-zA-Z\x{4e00}-\x{9fa5}]+(,[0-9a-zA-Z\x{4e00}-\x{9fa5}]+)*$/u',$str)){
			return $this->apiReturnErr('仅允许中文数字字母');
		}
		//过滤
		if(false === apiCall(FilterKeyWordsApi::CHECK,$str)){
			return $this->apiReturnErr('含有敏感词');
		}
		return $this->apiReturnSuc('pass');
	}

	public function getRandIds($start,$end,$num){
		$arr = [];
		for ($i=0; $i < $num; $i++) {
			$tmp = mt_rand($start,$end);
			while(in_array($tmp,$arr)){
        $tmp = mt_rand($start,$end);
      }
			// trace('---tmp'.$tmp);
      $arr[] = $tmp;
		}
		return $arr;
	}
}